const Router = require('koa-router');
const { pool } = require('../config/db');
const authMiddleware = require('../middleware/auth');

const router = new Router({ prefix: '/settings' });

// 前台：获取所有全局配置
router.get('/', async (ctx) => {
  const [rows] = await pool.query('SELECT setting_key, setting_value FROM settings');
  ctx.body = { data: rows.reduce((acc, item) => {
    acc[item.setting_key] = item.setting_value;
    return acc;
  }, {}) };
});

// 后台：创建配置项
router.post('/', authMiddleware, async (ctx) => {
  const { setting_key, setting_value, description } = ctx.request.body;
  const [result] = await pool.query('INSERT INTO settings (setting_key, setting_value, description) VALUES (?, ?, ?)', [setting_key, setting_value, description]);
  ctx.status = 201;
  ctx.body = { id: result.insertId, message: '配置项创建成功' };
});

// 后台：更新配置项
router.put('/:id', authMiddleware, async (ctx) => {
  const { id } = ctx.params;
  const { setting_value, description } = ctx.request.body;
  await pool.query('UPDATE settings SET setting_value=?, description=? WHERE id=?', [setting_value, description, id]);
  ctx.body = { message: '配置项更新成功' };
});

// 后台：删除配置项
router.delete('/:id', authMiddleware, async (ctx) => {
  await pool.query('DELETE FROM settings WHERE id=?', [ctx.params.id]);
  ctx.body = { message: '配置项删除成功' };
});

module.exports = router;